// pages/shareadd/shareadd.js
let that,
  api = new(require('../../utils/api.js')),
  myrecord = wx.getRecorderManager(),
  t,
  myaudio;
 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timing:0,
    piclist: [],
    count: 9,
    contents: '',
    uploading: !1,
    showaudio: 0,
    isrecord: 0,
    audiosrc: '',
    audioinfo: '',
    audioisplay: 0,
    videosrc:'',
    videoinfo:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    
    this.getsetting();
  },
  //录视频
  choosevideo(){
    if(that.data.videoinfo!=''){
      wx.showModal({
        showCancel: 0,
        title:'提示',
        content:'限添加一条视频'
      })
      return
    }
    if(that.data.piclist!=''||that.data.audioinfo!=''){
      wx.showModal({
        showCancel: 0,
        title:'提示',
        content:'限添加图片、音频、视频中的一种'
      })
      return
    }
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 15,
      camera: 'back',
      success(res) {
        console.log(res,'chooseVideo-res')
        console.log(res.tempFilePath,'viviviviiv')
        res.duration = Math.floor(res.duration)
        if(res.duration>15){
          wx.showModal({
            showCancel: 0,
            title:'提示',
            content:'视频最多只能有15秒'
          })
          return
        }
        that.setData({
          videoinfo:res,
        })
        
        
      }
    })
  },
  //
  deleteaudio() {
    that.setData({
      audioinfo: '',
      audioisplay: 0,
      isrecord: 0,
      audiosrc: '',
    })
  },
  //
  deletevideo(){
    that.setData({
      videoinfo:''
    })
  },
  playaudio() {
    myaudio.play(),
      that.setData({
        audioisplay: 1
      })
  },
  stopaudio() {
    myaudio.stop(),
      that.setData({
        audioisplay: 0
      })
  },
  startHandel(e) {
     t=setInterval(()=>{
      let{timing}=that.data
      that.setData({
        timing:timing+1
      })
    },1000)
    console.log(e, '开始录音')
    that.setData({
      isrecord: 1
    })
    myrecord.start()
  },
  endHandle(e) {
    console.log(e, '停止录音')
    clearInterval(t)
    that.setData({
      timing:0,
      isrecord: 0,
      showaudio: 0
    })
    myrecord.stop()
  },
  getsetting() {
    api.getsetting(res => {
      if (res.data.issuccess == 1) {
        let setting = res.data.data,
          count = setting.piccount;
        wx.setStorageSync("setting", setting)
        this.setData({
          count
        });
      }
    });
  },
  sub() {
    var {
      piclist,
      contents,
      videoinfo,
      audioinfo,uploading
    } = this.data;
    // if (contents == '') {
    //   wx.showModal({
    //     showCancel: !1,
    //     title: '提示',
    //     content: '请添加内容',
    //   })
    //   return;
    // }
    if (piclist == ''&&videoinfo==''&&audioinfo==''&&contents == '') {
      wx.showModal({
        showCancel: !1,
        title: '提示',
        content: '请添加图片',
      })
      return;
    }else if(piclist == ''&&videoinfo==''&&audioinfo==''){
      if(!uploading){
      that.setData({uploading:!0 });
      let data = {
        piclist: '',
        contents,
        audio:'',
        video:'',
      }
        api.addcomments(data,res=>{
          
          if (res.data.issuccess == 1) {
            wx.showToast({
              title:'提交成功',
              icon:'none',
              duration:1000,
            })
            let page  = getCurrentPages();
            page = page[page.length-2]
            page.setData({needupdate:!0},res=>{
              setTimeout(function () {
                that.setData({uploading:!1 });
                wx.navigateBack()
              },1000)
              // wx.redirectTo({
              //   url: '../share/share',
              // })
            })
          }else if(res.data.issuccess==-2)
          {
            that.setData({uploading:!1 });
            wx.showToast({
              title:'抱歉，您的评论内容包含敏感词，提交失败',
              icon:'none'
            })
          }else{
            that.setData({uploading:!1 });
          }
        })
      }
    }
    // if (piclist == ''&&videoinfo==''&&audioinfo=='') {
    //   wx.showModal({
    //     showCancel: !1,
    //     title: '提示',
    //     content: '请添加图片、视频、音频中的一种',
    //   })
    //   return;
    // }
    // if(contents!=''){
    //   let data = {
    //     piclist: '',
    //     contents,
    //     audio:'',
    //     video:'',
    //   }
    //   api.addcomments(data,res=>{
    //     if (res.data.issuccess == 1) {
    //       wx.showModal({
    //         showCancel: 0,
    //         content:'提交成功'
    //       })
    //       let page  = getCurrentPages();
    //       page = page[page.length-2]
    //       page.setData({needupdate:!0},res=>{
    //         wx.switchTab({
    //           url: '../share/share',
    //         })
    //       })
    //     }else if(res.data.issuccess==-2)
    //     {
    //       wx.showToast({
    //         title:'抱歉，您的评论内容包含敏感词，提交失败',
    //         icon:'none'
    //       })
    //     }
    //   })
    // }
    if(!uploading){
      that.setData({uploading:!0 });
      if(videoinfo!=""){
        wx.uploadFile({
          header: {
            'content-type': "application/x-www-form-urlencoded",
            token: getApp().logininfo.Token,
            userid: getApp().logininfo.userid
          },
          url: 'https://jianaijia.com/api/upload/wx_uploadvideo',
          name: 'upload',
          filePath: videoinfo.tempFilePath,
          success(res){
            const videores=JSON.parse(res.data)
            if(videores.issuccess==1){
              let data={
                contents,
                video:videores.path
              }
              api.addcomments(data,res=>{
                that.setData({uploading:!1 });
                if (res.data.issuccess == 1) {
                  wx.showToast({
                    title:'提交成功',
                    icon:'none',
                    duration:1000,
                  })
                  let page  = getCurrentPages();
                  page = page[page.length-2]
                  page.setData({needupdate:!0},res=>{
                    setTimeout(function () {
                      wx.navigateBack()
                    },1000)
                  })
                }else if(res.data.issuccess==-2)
                {
                  wx.showToast({
                    title:'抱歉，您的评论内容包含敏感词，提交失败',
                    icon:'none'
                  })
                }
              })
            }else{
              that.setData({uploading:!1 });
              return
            }
          },
          fail(res){
            that.setData({uploading:!1 });
          }
        })
      }
      if(audioinfo!=""){
        wx.uploadFile({
          header: {
            'content-type': "application/x-www-form-urlencoded",
            token: getApp().logininfo.Token,
            userid: getApp().logininfo.userid
          },
          url: 'https://jianaijia.com/api/upload/wx_uploadaudio',
          name: 'upload',
          filePath: audioinfo.tempFilePath,
          success(res){
            console.log(res,'auauauaauu')
            const audiores=JSON.parse(res.data);
            if(audiores.issuccess==1){
              let data={
                contents,
                audio:audiores.path,
                audioduration:audioinfo.duration
              }
              console.log(data,'dadaad')
              api.addcomments(data,res=>{
                that.setData({uploading:!1 });
                if (res.data.issuccess == 1) {
                  wx.showToast({
                    title:'提交成功',
                    icon:'none',
                    duration:1000,
                  })
                  let page  = getCurrentPages();
                  page = page[page.length-2]
                  page.setData({needupdate:!0},res=>{
                    setTimeout(function () {
                      wx.navigateBack()
                    },1000)
                  })
                  
                }else if(res.data.issuccess==-2)
                {
                  wx.showToast({
                    title:'抱歉，您的评论内容包含敏感词，提交失败',
                    icon:'none'
                  })
                }
              })
            }else{
              that.setData({uploading:!1 });
              return
            }
          },
          fail(res){
            that.setData({uploading:!1 });
          }
        })
      }
      // if (piclist.length <= 0) {
      //   wx.showModal({
      //     showCancel: !1,
      //     title: '提示',
      //     content: '请上传图片',
      //   })
      //   return;
      // }
  
      //上传图片
      if(piclist.length>0){
        api.uploadimg({
          url: 'https://jianaijia.com/api/upload/wx_upload', //这里是你图片上传的接口
          path: piclist //这里是选取的图片的地址数组        
        }, {
          success: function (res) {
            if (res.length == piclist.length) {
              console.log("全部上传");
              let pics = res.join(",");
              let data = {
                piclist: pics,
                contents,
                audio:'',
                video:'',
              }
              console.log(data);
              api.addcomments(data,res=>{
                that.setData({uploading:!1 });
                if (res.data.issuccess == 1) {
                  wx.showToast({
                    title:'提交成功',
                    icon:'none',
                    duration:1000,
                  })
                  let page  = getCurrentPages();
                  page = page[page.length-2]
                  page.setData({needupdate:!0},res=>{
                    setTimeout(function () {
                      wx.navigateBack()
                    },1000)
                  })
                }else if(res.data.issuccess==-2)
                {
                  wx.showToast({
                    title:'抱歉，您的评论内容包含敏感词，提交失败',
                    icon:'none'
                  })
                }
              })
            } else {
              that.setData({uploading:!1 });
              wx.showModal({
                title: '提示',
                content: '上传图片失败',
              })
              that.setData({
                piclist: []
              });
            }
            
          },
          fail(res){
            that.setData({uploading:!1 });
          }
        });
      }
    }
},
  inputchange(e) {
    var proval = {},
      {
        prop
      } = e.target.dataset;
    proval[prop] = e.detail.value;
    // console.log(proval,prop);
    this.setData(proval);

  },
  showaudio() {
    if(that.data.audioinfo!=''){
      wx.showModal({
        showCancel: !1,
        title: '提示',
        content: '限添加一条音频',
      })
      return;
    }
    if(that.data.piclist!=''||that.data.videoinfo!=''){
      wx.showModal({
        showCancel: 0,
        title:'提示',
        content:'限添加图片、音频、视频中的一种'
      })
      return
    }
    that.setData({
      showaudio: 1
    })
    myrecord.onStart(() => {
      console.log('正在录音中')
    })
    myrecord.onStop((res) => {
      console.log('录音结束', res)
      const tempFilePath = res.tempFilePath;
      res.duration = Math.floor(res.duration / 1000);
      if(res.duration<1){
        wx.showModal({
          showCancel: 0,
          title:'提示',
          content:'录音时间不能少于1秒'
        })
        return
      }
      if(res.duration>60){
        wx.showModal({
          showCancel: 0,
          title:'提示',
          content:'录音时间不能大于60秒'
        })
        return
      }
      that.setData({
        audioinfo: res
      });
      if (myaudio == null) {
        myaudio = wx.createInnerAudioContext();
        console.log('实例已经创建')

      }
      myaudio.src = tempFilePath;
      myaudio.onPlay(() => {
        console.log('开始播放录音')
      })
      myaudio.onStop(() => {
        console.log('停止播放录音')
      })
      myaudio.onEnded(() => {
        console.log('录音自然播放结束')
        that.setData({
          audioisplay: 0
        })
      })
      myaudio.play()
      wx.playVoice({
        success(){
          console.log(tempFilePath,'tempFilePathtempFilePath')
        },
        filePath:tempFilePath,
        complete(){
          console.log('播放完成')
        }
      })
    })
  },

  cancelshowaudio() {
    that.setData({
      showaudio: 0
    })
  },
  previewimage(e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current,
      urls: this.data.piclist
    })
  },
  chooseimage() {
    if(that.data.audioinfo!=''||that.data.videoinfo!=''){
      wx.showModal({
        showCancel: 0,
        title:'提示',
        content:'限添加图片、音频、视频中的一种'
      })
      return
    }
    let {
      piclist,
      count
    } = this.data;
    wx.chooseImage({
      count: count - piclist.length,
      success: function (res) {
        piclist = piclist.concat(res.tempFilePaths);
        that.setData({
          piclist
        })
      }
    })
  },
  del(e) {
    let {
      index
    } = e.target.dataset, {
      piclist
    } = this.data;

    piclist.splice(index, 1);
    this.setData({
      piclist
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})